import { AxiosInstance } from 'axios';

import { TokenUtil } from '../http/utils/TokenUtil';
import { log } from '../http/utils/log';
import { accountService } from './security/Account';

/**
 * @author 戴俊明 <idaijunming@163.com>
 * @description axios Token拦截器
 * @date 2019/11/21 20:47
 **/

export interface Interceptor {
	(instance: AxiosInstance): void;
}

export const tokenInterceptor: Interceptor = (
	instance: AxiosInstance
): void => {
	instance.interceptors.request.use(
		config => {
			if (TokenUtil.get()) {
				config.headers = { Authorization: TokenUtil.get(), ...config.headers };
			}
			return config;
		},
		error => error
	);
	instance.interceptors.response.use(
		resp => {
			if (resp.headers.Authorization) {
				TokenUtil.set(resp.headers.Authorization);
			}
			if (resp.headers.AuthorizationUpgrade) {
				// eslint-disable-next-line @typescript-eslint/no-empty-function
				accountService.upgradeInfo().then(() => {});
			}
			log(resp);
			return resp;
		},
		// 返回请求错误的响应
		error => {
			log(error.response);
			return error;
		}
	);
};
